package com.longrise.android.byjk.plugins.hra.hratabfirst;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.haibin.calendarview.Util;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.event.HraDateEvent;
import com.longrise.android.byjk.plugins.hra.hratabfirst.hradetailweb.HraDetailX5webActivity;
import com.longrise.android.byjk.widget.view.BBswipeRefreshLayout;
import com.longrise.common.base.BaseFragment;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.utils.PrintLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2018/1/3.
 * HRA预约
 */

public class HraOrderFragment extends BaseFragment<HraOrderPresenter> implements
        HraOrderContract.View, View.OnClickListener, HraOrderRcvAdapter.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener {

    public static final String TAG = "HraOrderFragment";
    public static final int HRAORDERFRAGMENT = 1;
    private RecyclerView miRV;
    private BBswipeRefreshLayout mSwipeRefreshLayout;
    private LinearLayout mHeaderView = null;
    private HraOrderRcvAdapter hraOrderRcvAdapter;
    private float mBannerHeight;
    private ImageView mHraOrderIv;
    private int mDistanceY;
    private RelativeLayout mHraSelect;
    private LinearLayout mDateSelect;
    private LinearLayout mLlDataSelect;
    private int mYear;
    private int mMonth;
    private int mDay;
    private TextView mTvHeadDate;
    private TextView mTvDate;
    private LinearLayoutManager mLinearLayoutManager;
    private Toolbar mToolbar;
    private String areaId = "110108";   //地区id
    private String bespeakdate = "";   //日期
    //    private EntityBean[] mHraListBean;
    private String time;
    private String hrapicurl = "http://download.yxybb.com/project/INSHWEB/images/app/hraindex_banner.png";   //Hra预约首页头部图片
    private List<HraOrderDefaultItem> mOrderDefaultItemList = new ArrayList<>();

    @Override
    protected int getLayoutResourse(@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_hra_order;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        mToolbar = (Toolbar) mRootView.findViewById(R.id.byjk_toolbar);
        mToolbar.setTitle("HRA预约");
        miRV = (RecyclerView) mRootView.findViewById(R.id.hra_fragment_irv);
        mSwipeRefreshLayout = (BBswipeRefreshLayout) mRootView.findViewById(R.id.hra_fragment_swipelayout);
        mHraSelect = (RelativeLayout) mRootView.findViewById(R.id.ll_hra_select);
        mLlDataSelect = (LinearLayout) mRootView.findViewById(R.id.ll_date_selection);
        mTvDate = (TextView) mRootView.findViewById(R.id.hra_pinner_header_date_tv);

        //头部viewpager
        mHeaderView = (LinearLayout) View.inflate(mContext, R.layout.header_hraview, null);
        mHraOrderIv = (ImageView) mHeaderView.findViewById(R.id.iv_hra_header);
        mDateSelect = (LinearLayout) mHeaderView.findViewById(R.id.ll_date_selection);
        mTvHeadDate = (TextView) mHeaderView.findViewById(R.id.hra_pinner_header_date_tv);

        initVp();
        initHraRev();
        initData();
        initEvent();
        mPresenter.getDataFromNet(areaId, bespeakdate);
    }

    private void initEvent() {
        mLlDataSelect.setOnClickListener(this);
        mHraOrderIv.setOnClickListener(this);
        mDateSelect.setOnClickListener(this);
        hraOrderRcvAdapter.setOnItemClickListener(this);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
    }

    /**
     * 初始化头部的图片
     */
    private void initVp() {
        int width = AppUtil.getScreenWidth();
        mBannerHeight = (float) width * 120 / 375;
        ViewGroup.LayoutParams layoutParams = mHraOrderIv.getLayoutParams();
        layoutParams.height = (int) mBannerHeight;
        mHraOrderIv.setLayoutParams(layoutParams);
        Glide.with(mContext)
                .load(hrapicurl)
                .crossFade()
                .into(mHraOrderIv);
    }

    //初始化数据用于测试
    public void initData() {

        //切换数据之后移动到列表第一位,同时将滑动距离设置为0
//        miRV.smoothScrollToPosition(0);
        miRV.scrollToPosition(0);
        mDistanceY = 0;

        //----------- 关于日历 ---- end ------
        Date d = new Date();
        mYear = Util.getDate("yyyy", d);
        mMonth = Util.getDate("MM", d);
        mDay = Util.getDate("dd", d);
        setDate(mMonth, mDay);
        //----------- 关于日历-- end ----------
        String time = mYear + "-" + mMonth + "-" + mDay + "";
        bespeakdate = Util.getMyDate(time);
    }

    //初始化整体recyclerview
    private void initHraRev() {
        hraOrderRcvAdapter = new HraOrderRcvAdapter(getDefatutData());
        mLinearLayoutManager = new LinearLayoutManager(mContext);
        miRV.setLayoutManager(mLinearLayoutManager);
        miRV.setAdapter(hraOrderRcvAdapter);
        hraOrderRcvAdapter.setHeaderView(mHeaderView);

        //滑动监听
        miRV.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                //banner高度大于滑动距离,跟随滑动
                mDistanceY += dy;
                PrintLog.d(TAG, "dy:" + dy + "---" + "mDistanceY:" + mDistanceY);
                if (mBannerHeight >= mDistanceY) {
                    mHraSelect.setVisibility(View.GONE);
                } else {
                    mHraSelect.setVisibility(View.VISIBLE);
                }

            }
        });

    }

    /**
     * 数据还没加载出来的时候 显示的假数据
     */
    private List<HraOrderDefaultItem> getDefatutData() {
        mOrderDefaultItemList.clear();
        for (int x = 0; x < 1; x++) {
            HraOrderDefaultItem item = new HraOrderDefaultItem(HraOrderDefaultItem.TYPE1);
            mOrderDefaultItemList.add(item);
        }
        return mOrderDefaultItemList;
    }


    @Override
    public void showLoadingDialog() {

    }

    @Override
    public void dismissLoadingDialog() {

    }

    @Override
    public void onRefresh() {
        mPresenter.getDataFromNet(areaId, bespeakdate);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //点击图片
            case R.id.iv_hra_header:
                Intent intent = new Intent(getActivity(), HraDetailX5webActivity.class);
                getActivity().startActivity(intent);
                break;
            //点击弹出日历
            case R.id.ll_date_selection:
                toShowCalendar();
                break;
        }
    }

    @Override
    public void onItemClick(String storeid) {
        jump2HraServiceDetail(storeid);
    }

    public void jump2HraServiceDetail(String storeid) {
        Intent intent = new Intent(mContext, HraServiceDetailActivity.class);
        intent.putExtra(HraServiceDetailActivity.STOREID, storeid);
        intent.putExtra(HraServiceDetailActivity.BESPEAKDATE, bespeakdate);
        intent.setFlags(HRAORDERFRAGMENT);
        startActivity(intent);
    }

//-------------------------- 关于日历 ----- start -------------------------------------

    /**
     * 显示日历
     */
    private void toShowCalendar() {
        CalendarDialogFragment fragment = CalendarDialogFragment.newInstance(mYear, mMonth, mDay, 3);
        fragment.show(getFragmentManager(), "hradialogfragment");
    }

    /**
     * 设置head 和覆盖view上面的日期
     */
    private void setDate(int month, int day) {
        mTvDate.setText(month + "月" + day + "日");
        mTvHeadDate.setText(month + "月" + day + "日");
    }

    /**
     * 获取 选择到的日期
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeDateEvent(HraDateEvent event) {
        int pageNum = event.getPageNum();
        if (3 == pageNum){
            mYear = event.getYear();
            mMonth = event.getMonth();
            mDay = event.getDay();
            setDate(mMonth, mDay);
            time = mYear + "-" + mMonth + "-" + mDay + "";
            bespeakdate = Util.getMyDate(time);

            mPresenter.getDataFromNet(areaId, bespeakdate);
        }
    }

//-------------------------- 关于日历 ----- end -------------------------------------


    @Override
    public void refreshData(EntityBean bean) {
        EntityBean[] results = bean.getBeans("result");
        mOrderDefaultItemList.clear();
        if (results == null) {

            //重新将recyclerview定位到顶部
            mLinearLayoutManager.scrollToPositionWithOffset(0, 0);
            mDistanceY = 0;
            mHraSelect.setVisibility(View.GONE);
            //--------------------
            hraOrderRcvAdapter.refreshDatas(getDefatutData());
        } else {
            //重新将recyclerview定位到顶部
            mLinearLayoutManager.scrollToPositionWithOffset(0, 0);
            mDistanceY = 0;
            mHraSelect.setVisibility(View.GONE);
            //--------------------
            for (EntityBean resultBean : results) {
                HraOrderBean childBean = new HraOrderBean();
                childBean.setHraName(resultBean.getString("storename"));
                childBean.setPriceType1(resultBean.getString("price1"));
                childBean.setPriceType2(resultBean.getString("price2"));
                childBean.setStoreId(resultBean.getString("storeid"));
                childBean.setLeftCounts(resultBean.getString("stockpeople"));

                HraOrderDefaultItem item = new HraOrderDefaultItem(HraOrderDefaultItem.TYPE2);
                item.setHraOrderBean(childBean);
                mOrderDefaultItemList.add(item);
            }
            hraOrderRcvAdapter.refreshDatas(mOrderDefaultItemList);
        }
    }

    @Override
    public void refreshSelectData(EntityBean bean) {

    }

    @Override
    public void setRefreshing(boolean isRefreshing) {
        mSwipeRefreshLayout.setRefreshing(isRefreshing);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
